package com.partybuilding.listener;
import com.alibaba.excel.context.AnalysisContext;

import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.partybuilding.domain.entity.Usertable;
import com.partybuilding.domain.vo.UserCheckVo;
import com.partybuilding.service.UsertableService;
import com.partybuilding.service.impl.UsertableServiceImpl;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author wulala
 * 监听器，用于读取excel数据
 */
@Slf4j
@Component
public class EasyExcelOrderListener extends AnalysisEventListener<UserCheckVo> {

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    /**
     * 缓存的数据
     */
    private List<UserCheckVo> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    private UsertableService usertableService;

    public EasyExcelOrderListener(UsertableService usertableService) {
        // 这里是demo，所以随便new一个。实际使用如果到了spring,请使用下面的有参构造函数
        this.usertableService =  usertableService;
    }

    /**
     * 此方法每一条数据解析都会来调用
     *
     */
    @Override
    public void invoke(UserCheckVo userCheckVo, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", JSON.toJSONString(userCheckVo));
        cachedDataList.add(userCheckVo);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            usertableService.uploadAllData(cachedDataList);
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }
    /**
     * 所有数据解析完成都会来调用
     *
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        usertableService.uploadAllData(cachedDataList);
        log.info("所有数据解析完成！！！");
    }


}
